import React, { useState, useEffect } from 'react';
import { Card, Table, Button, Space, Tag, message, Modal, Form, Input } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, CrownOutlined } from '@ant-design/icons';
import { getBrandList, type BrandItem } from '@/services/products';

interface ProductBrand extends BrandItem {
  id: number;
  slug: string;
  description: string;
  logo_url?: string;
  website?: string;
  created_at: string;
}

const ProductBrands: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [brands, setBrands] = useState<ProductBrand[]>([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingBrand, setEditingBrand] = useState<ProductBrand | null>(null);
  const [form] = Form.useForm();

  // 表格列配置
  const columns = [
    {
      title: 'Logo',
      dataIndex: 'logo_url',
      key: 'logo_url',
      width: 80,
      render: (logoUrl: string, record: ProductBrand) => (
        logoUrl ? (
          <img 
            src={logoUrl} 
            alt={record.brand}
            style={{ width: 40, height: 40, objectFit: 'contain' }}
          />
        ) : (
          <div 
            className="flex items-center justify-center bg-gray-100 text-gray-400"
            style={{ width: 40, height: 40, borderRadius: 4 }}
          >
            {record.brand.charAt(0).toUpperCase()}
          </div>
        )
      ),
    },
    {
      title: '品牌名称',
      dataIndex: 'brand',
      key: 'brand',
      width: 150,
    },
    {
      title: '官网',
      dataIndex: 'website',
      key: 'website',
      width: 120,
      render: (website: string) => (
        website ? (
          <a href={website} target="_blank" rel="noopener noreferrer">
            访问官网
          </a>
        ) : (
          '-'
        )
      ),
    },
    {
      title: '产品数量',
      dataIndex: 'product_count',
      key: 'product_count',
      width: 100,
      render: (count: number) => (
        <Tag color={count > 0 ? 'blue' : 'default'}>
          {count}
        </Tag>
      ),
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right' as const,
      width: 150,
      render: (record: ProductBrand) => (
        <Space>
          <Button
            type="link"
            size="small"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button
            type="link"
            size="small"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  // 获取品牌列表
  const fetchData = async () => {
    try {
      setLoading(true);
      const data = await getBrandList();
      
      // 转换数据格式以匹配表格显示需求
      const formattedBrands: ProductBrand[] = data.map((item, index) => ({
        id: index + 1, // 临时ID，因为API返回的数据没有ID
        brand: item.brand,
        product_count: item.product_count,
        slug: item.brand.toLowerCase().replace(/\s+/g, '-'),
        description: `${item.brand}品牌产品`,
        logo_url: '', // API暂不提供
        website: '', // API暂不提供
        created_at: new Date().toISOString(),
      }));
      
      setBrands(formattedBrands);
    } catch (error) {
      console.error('获取品牌列表失败:', error);
      message.error('获取品牌列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 事件处理
  const handleAdd = () => {
    message.info('品牌管理功能正在开发中，请等待后端接口完善');
    // setEditingBrand(null);
    // form.resetFields();
    // setModalVisible(true);
  };

  const handleEdit = (record: ProductBrand) => {
    message.info('编辑品牌功能正在开发中，请等待后端接口完善');
    // setEditingBrand(record);
    // form.setFieldsValue(record);
    // setModalVisible(true);
  };

  const handleDelete = (record: ProductBrand) => {
    message.info('删除品牌功能正在开发中，请等待后端接口完善');
    // Modal.confirm({
    //   title: '确认删除',
    //   content: `确定要删除品牌 "${record.brand}" 吗？`,
    //   onOk: () => {
    //     message.success('删除成功');
    //     fetchData();
    //   },
    // });
  };

  const handleModalOk = () => {
    form.validateFields().then(values => {
      console.log('Form values:', values);
      message.success(editingBrand ? '更新成功' : '创建成功');
      setModalVisible(false);
      fetchData();
    });
  };

  useEffect(() => {
    fetchData();
  }, []);

  return (
    <div className="p-6">
      <Card>
        <div className="mb-4 flex justify-between items-center">
          <h2 className="text-xl font-semibold flex items-center">
            <CrownOutlined className="mr-2" />
            品牌管理
          </h2>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={handleAdd}
          >
            添加品牌
          </Button>
        </div>

        <Table
          columns={columns}
          dataSource={brands}
          loading={loading}
          rowKey="brand"
          pagination={{
            total: brands.length,
            showTotal: (total) => `共 ${total} 条记录`,
            showSizeChanger: true,
            showQuickJumper: true,
          }}
          scroll={{ x: 800 }}
        />
      </Card>

      <Modal
        title={editingBrand ? '编辑品牌' : '添加品牌'}
        open={modalVisible}
        onOk={handleModalOk}
        onCancel={() => setModalVisible(false)}
        width={500}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="name"
            label="品牌名称"
            rules={[{ required: true, message: '请输入品牌名称' }]}
          >
            <Input placeholder="请输入品牌名称" />
          </Form.Item>

          <Form.Item
            name="slug"
            label="别名"
            rules={[{ required: true, message: '请输入别名' }]}
          >
            <Input placeholder="请输入别名（英文，用于URL）" />
          </Form.Item>

          <Form.Item
            name="description"
            label="描述"
            rules={[{ required: true, message: '请输入描述' }]}
          >
            <Input.TextArea placeholder="请输入描述" rows={3} />
          </Form.Item>

          <Form.Item
            name="logo_url"
            label="Logo URL"
          >
            <Input placeholder="请输入Logo图片URL" />
          </Form.Item>

          <Form.Item
            name="website"
            label="官方网站"
          >
            <Input placeholder="请输入官方网站地址" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default ProductBrands; 